<?php
/** 
* 用户模块控制器文件
* 
* 用户操作和数据的获取
* @author      sinalma  <sinalma@foxmail.com>
* @version     1.0 版本号
*/ 
namespace app\index\controller;

use think\Controller;
use think\View;
use app\index\model\User as UserModel;
use think\Session;
use app\common\tools\ID as IDObj;


/** 
 * Class User
 * 用户控制器 
 *
 * @package app\index\controller
 * @author      sinalma  <sinalma@foxmail.com>
 * @version     1.0 版本号
 */ 
class User extends Controller
{
    private $htpURL = '';

    public function uploadPic(){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('image');
        
        if($file){
            $info = $file->move(ROOT_PATH . 'public'. DS .'static' . DS . 'uploads' . DS .'profile' . DS );
            if($info){
                // echo $info->getExtension();
                // echo $info->getFilename(); 
                $filePath = "{$this->htpURL}/public/static/uploads/profile/".$info->getSaveName();
                $user = Session::get('user');
                UserModel::where('uid', $user['uid'])->update(['profile_pic' => $filePath]);
                $user_n = UserModel::get(['uid' => $user['uid']]);
                Session::delete('user');
                Session::set('user',$user_n);
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
                // return false;
            }
            return $this->fetch('user');
        } 
    }



    public function clip(){
        return $this->fetch();
    }



    /**  
     * 显示用户中心界面
     * 
     * @access public 
     */  
    public function user(){
        if (!SESSION::get('user')) {
            
            $this->redirect("../../index"); 
        }
        return $this->fetch();
    }

    /**  
     * 显示用户注册界面
     * 
     * @access public 
     */       
  	public function register()
  	{
  		  return $this->fetch();
  	}


    /**  
     * 显示用户登录界面
     * 
     * @access public 
     */       
  	public function login()
  	{
  		  return $this->fetch();
  	}

    /**  
     * 获取登录或注册html
     * 
     * @access public 
     * @param $type 登录or注册("login"or"register")
     * @return html
     */ 
    public function getFormHtml($type){
        $in_type = "";
        $btnStr = "";
        if ($type==="login"){
            $in_type = "checkAcc";
            $btnStr = "Sign In";
        }else if($type==="register") {
            $in_type = "registerAcc";
            $btnStr = "Sign Up";
        }
        $html = "";

$html .= <<<eof
<div class="overCurtain"></div>
<div class="hide-center">
    <div id="formhead">
        <div id="formhead-title">
            ${type}
        </div>
        <button type="button" id="close">X</button>
    </div>
    <div id="formbody">
        <div class="loginUserName">
            <input id="input-topright-loginInput" name="username"  class="username loginInput" placeholder="username" type="text">
        </div>
        <div class="loginPassword">
            <input id="input-bottomright-loginInput" name="password"  class="password loginInput" placeholder="password" type="password" style="border-bottom-right-radius:5px;">
        </div>
        <div id="formfoot">
            <button id="BSignIn" type="submit">{$btnStr}</button>
        </div>
    </div>
    <script type="text/javascript">
    function showLogin(){
        $(".hide-center").fadeIn("slow");
        $(".overCurtain").fadeIn("slow");
        var top = $(window).scrollTop();
        $(".overCurtain").css('top',top); 
    }
    function closeLogin(){
        $(".overCurtain").fadeOut("slow");
        $(".hide-center").fadeOut("slow");
        $('body').css('overflow','auto'); 
        $(".overCurtain").remove();
        $(".hide-center").remove();
    }
    $("#close").click(function () {
        closeLogin();
    })
    $(".username").blur(function(){
    if ('{$type}' == "register"){
        var username = $('.username').val();
        if(username.length <= 0){
            // setTimeout(function() {
            // $.hulla.send("用户名不能为空", "warning");}, 100);
            return;
        }
        $.ajax({
            url:"{$this->htpURL}/index/user/verifyUsername",
            data:{username:username},
            type:"post",
            dataType:"json",
            success:function(data){
                setTimeout(function() {
                $.hulla.send(data, "info");}, 100);
            },
            error:function(){
                setTimeout(function() {
                $.hulla.send("请求失败,请刷新页面重新注册", "warning");}, 100);
            }
        })
    }
    });
    // 提交表单信息到后台,处理注册信息
    $('#BSignIn').click(function(evt){
        var username = $('.username').val();
        var password = $('.password').val();
        if(username.length < 3 || username.length > 32){
            setTimeout(function() {
                $.hulla.send("用户名长度必须在3-32位之间", "warning");}, 100);
            return;
        }
        if(password.length < 6 || password.length > 64){
            setTimeout(function() {
                $.hulla.send("密码长度必须在6-64位之间", "warning");}, 100);
            return;
        }
        $.ajax({
            url:"{$this->htpURL}/index/user/{$in_type}",
            data:{username:username,password:password},
            type:"post",
            dataType:"json",
            success:function(data){
                $("#main-container").append(data);
                closeLogin();
            },
            error:function(){
                alert('失败了');
            }
        })
    });
    $("body").click(function(){closeLogin()});
    // 当操作在表单框内,阻止触发body响应动作
    $(".hide-center").click(function(event){
        event.stopPropagation();
    });
    </script>
</div>
eof;
        return $html;
    }


    /**  
     * 退出当前登录的用户
     * 
     * @access public 
     * @return null
     */ 
    public function logout(){
        Session::delete('user');
    }

    
    /**  
     * 获取注册页面
     * 
     * @access public 
     * @return html
     */ 
    public function alertRegister(){
        return $this->getFormHtml("register");
    }

    /**  
     * 获取登录页面
     * 
     * @access public 
     * @return html
     */ 
    public function alertLogin(){
        return $this->getFormHtml("login");
    }


    /**  
     * 验证用户名是否已经存在(暂时用于注册)
     * 
     * @access public
     * @return username POST参数 用户名 
     * @return string
     */ 
    public function verifyUsername(){
        $usrn = input('post.username');
        $user = UserModel::get(['user_name' => $usrn]);
        if($user){
            return $user->user_name."已被注册,请重新输入!";
        }else{
            return "恭喜您,可以使用".$usrn."注册";
        }
    }

    /**  
     * 用户登录,校验用户名和账号
     * 
     * @param 需要传递post参数username，password
     * @access public 
     * @return view
     */       
	public function checkAcc(){
		$userModel = new UserModel();
        $usrn = input('param.username');
        $pwd = md5(input('param.password'));
        $res = $userModel->check($usrn,$pwd);
        if ($res){
            Session::delete('user','index');
            Session::set('user',$res);
            return "<script>setTimeout(function() {
                  $.hulla.send(\"登录成功\", \"success\");location.reload();}, 100);</script>";
        }else{
            return "<script>setTimeout(function() {
                  $.hulla.send(\"用户名或密码错误,请重新登录\", \"warning\");}, 100);</script>";
        }
	}


    /**  
     * 注册,将用户名和密码传入模型insert进数据库
     * 
     * @param 需要传递post参数username，password
     * @access public 
     * @return view
     */        
	public function registerAcc(){
        $userModel = new UserModel();
        $usrn = input('param.username');
        $pwd = md5(input('param.password'));
       
        $res = $userModel->register($usrn,$pwd);
        if ($res){
            return "<script>setTimeout(function() {
                  $.hulla.send(\"注册成功,请登录\", \"success\");eval(\"alertLogin\"+\"()\");}, 100);</script>";
        }else{
            return "<script>setTimeout(function() {
                  $.hulla.send(\"此用户名已被注册,请重新填写\", \"warning\");
                }, 100);</script>";
        }
	  }


    // 额外方法
    public function addAllProfile(){

        $um = new UserModel();
        $res = $um->query("SELECT id from sinblog_user_list");
        for ($i=0;$i<count($res);++$i){

            $id = $res[$i]['id'];
            $rand = mt_rand(100,299);
            $picUrl = "https://cdn.v2ex.com/gravatar/594f0e38ee46673f7ab6ee9b15{$rand}dd?d=identicon";
            $um->query("update sinblog_user_list set profile_pic='{$picUrl}' where id='{$id}'");
        }
    }
    public function addAllUID(){
        $um = new UserModel();
        $res = $um->query("SELECT id,reg_time from sinblog_user_list");
        for ($i=0;$i<count($res);++$i){
            $id = $res[$i]['id'];
            $reg_time = $res[$i]['reg_time'];
            $idobj = new IDObj();
            $uid = $idobj->enid($reg_time);
            $um->query("UPDATE sinblog_user_list set uid='{$uid}' where id='{$id}'");
        }
    }
}